//
//  UIImage+extensions.swift
//  YFSwiftWeibo
//
//  Created by tsaievan on 2017/9/8.
//  Copyright © 2017年 tsaievan. All rights reserved.
//

import UIKit

extension UIImage {
    func yf_drawInRect(size: CGSize?, backgroundColor: UIColor = UIColor.white, lineColor: UIColor = UIColor.lightGray)->UIImage? {
        
        var size = size
        if size == nil {
            size = self.size
        }
        let rect = CGRect(origin: CGPoint(), size: size!)
        
        ///< 1. 获取图形上下文
        UIGraphicsBeginImageContextWithOptions(rect.size, true, 0)
        backgroundColor.setFill()
        UIRectFill(rect)
        
        ///< 2. 切圆角
        let path = UIBezierPath(ovalIn: rect)
        path.addClip()
        
        ///< 3. 画图
        draw(in: rect)
        let ovalPath = UIBezierPath(ovalIn: rect)
        ovalPath.lineWidth = 2
        lineColor.setStroke()
        ovalPath.stroke()
        
        ///< 4. 得到图片对象
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        ///< 5. 关闭图形上下文
        UIGraphicsEndImageContext()
        
        return image
    }
}
